<script lang="ts" setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  import * as echarts from 'echarts/core';
  const props = defineProps({
    data1: { type: Object as () => any, required: true },
    data2: { type: Object as () => any, default: [] },
    data3: { type: Object as () => any, default: [] },
    datax: { type: Object as () => any, required: true },
    title: { type: String, default: '' },
    dataName: { type: Object as () => any, default: [] },
    max: { type: Number, default: 100 },
    min: { type: Number, default: 0 },
  });

  const chartRef = ref<HTMLElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;

  const option = ref<any>({
    title: {
      text: props.title,
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold',
        color: '#fff',
      },
    },
    tooltip: {
      trigger: 'axis',
      appendToBody: true, // 关键设置
      axisPointer: {
        type: 'shadow',
      },
    },
    bar: {
      barGap: '30%',
      barCategoryGap: '30%',
    },
    grid: {
      left: '5%',
      right: '4%',
      bottom: '0%',
      top: '20%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      data: props.datax,
      axisLabel: { color: '#fff' },
      axisLine: { lineStyle: { color: '#fff' } },
      splitLine: { show: false },
    },
    yAxis: {
      type: 'value',
      name: props.dataName[0] || '',
      axisLine: { lineStyle: { color: '#fff' } },
      scale: true,
      splitLine: { show: false },
    },
    series: [
      {
        name: props.dataName[0] || '',
        type: 'line',
        itemStyle: {
          color: '#5470c6', // 使用蓝色表示目标
        },
        data: props.data1,
        smooth: false,
        label: {
          show: true,
          position: 'top',
          color: '#fff',
          formatter: '{c}%',
        },
      },
    ],
  });

  const initCharts = () => {
    try {
      option.value.series[0].data = props.data1 ?? [];
      if (props.data2.length > 0) {
        option.value.series.push({
          name: props.dataName[1],
          type: 'line',
          itemStyle: {
            color: '#fac858', // 使用橙色表示实际
          },
          data: props.data2,
          smooth: false,
          label: {
            show: true,
            position: 'top',
          },
        });
      }
      if (props.data3.length > 0) {
        option.value.series.push({
          name: props.dataName[2],
          type: 'line',
          data: props.data3,
          itemStyle: {
            color: '#91cc75',
          },
          smooth: false,
          label: {
            show: true,
            position: 'top',
          },
        });
      }
      option.value.xAxis.data = props.datax ?? [];
      if (chartRef.value && !chartInstance) {
        chartInstance = echarts.init(chartRef.value);
        chartInstance?.setOption(option.value, true);
      }
    } catch (error) {
      console.error('图表初始化失败:', error);
    }
  };

  const updateChart = () => {
    option.value.series[0].data = props.data1 ?? [];
    if (props.data2.length > 0) {
      option.value.series.push({
        name: props.dataName[1],
        type: 'bar',
        itemStyle: {
          color: '#fac858', // 使用橙色表示实际
        },
        data: props.data2,
        smooth: false,
        label: {
          show: true,
          position: 'top',
        },
      });
    }
    if (props.data3.length > 0) {
      option.value.series.push({
        name: props.dataName[2],
        type: 'bar',
        data: props.data3,
        itemStyle: {
          color: '#91cc75',
        },
        smooth: false,
        label: {
          show: true,
          position: 'top',
        },
      });
    }
    option.value.xAxis.data = props.datax ?? [];
    chartInstance?.setOption(option.value, true);
    handleResize();
  };

  onMounted(() => {
    // 确保在 DOM 加载完成后更新图表
    setTimeout(() => {
      nextTick(() => {
        initCharts();
      });
    }, 100);

    // 添加窗口大小变化监听
    window.addEventListener('resize', updateChart);
  });

  onUnmounted(() => {
    // 移除窗口大小变化监听
    window.removeEventListener('resize', updateChart);
    chartInstance?.dispose();
  });

  watch(
    () => [props.datax, props.data1],
    () => updateChart(),
    { deep: true }
  );

  // 窗口大小变化处理
  const handleResize = () => {
    nextTick(() => {
      chartInstance?.resize();
    });
  };

  defineExpose({
    updateChart, // 暴露方法到父组件
    chartRef,
  });
</script>
<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<style scoped>
  .chart-container {
    width: 100%;
    height: 100%;
  }
</style>
